package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /*
        获取当前用户的地址集合
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        //获取当前用户的id
        Long userID = BaseContext.get();
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userID);
//        addressBookLambdaQueryWrapper.orderByDesc(AddressBook::getIsDefault);
        //根据用户id去查询当前用户的地址集合
        List<AddressBook> list = addressBookService.list(addressBookLambdaQueryWrapper);
        return R.success(list);
    }

    /*
        新增地址
     */
    @PostMapping
    public R save(@RequestBody AddressBook addressBook){
        //保存地址先设置好当前用户的id
        addressBook.setUserId(BaseContext.get());
        addressBookService.save(addressBook);
        return R.success(null);
    }
    /*
        修改的回显
     */
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);
    }
    /*
        修改
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success(null);
    }

    /*
        设置默认地址
     */
    @PutMapping("/default")
    public R defaultAddress(@RequestBody AddressBook addressBook){
        addressBookService.defaultAddress(addressBook);
        return R.success(null);
    }
    /*
        逻辑删除
     */
    @DeleteMapping
    public R deleteByids(@RequestParam List<Long > ids){
        addressBookService.removeByIds(ids);
        return R.success(null);
    }
    /*
        查询默认地址
     */
    @GetMapping("/default")
    public R<AddressBook> defaultAddressBook(){
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.get());
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        return R.success(addressBook);
    }
}
